<template>
  <div>
    <div style="clear:both;">
      <div style="float: left">
        羊场全称： <el-input v-model="SelTo.name" style="width: 200px;" clearable />&emsp;&emsp;
        负责人： <el-input v-model="SelTo.pname" style="width: 200px;" clearable />


      </div>
      <div style="float: right">
        <el-button size="large" type="danger" @click="LoadData">查询</el-button>
        <el-button size="large" onclick="location.reload();">重置</el-button>
      </div>
    </div>

    <br>
    <br>
    <br>
    <div style="clear:both;">
      <div style="float: left">
        <el-button size="large" type="danger" @click="AddNew"><el-icon>
            <Plus />
          </el-icon>&emsp;新增</el-button>
        <el-button size="large" type="danger" @click="DelAll"><el-icon>
            <Delete />
          </el-icon>&emsp;删除</el-button>
      </div>

      <!-- 当复选框选中之后变为白色时，不要慌张，请看右上角的颜色选择器，那zz玩意会把复选框的选中状态颜色给修改掉 -->
      <table style="float: right">
        <tr>
          <td onclick="location.reload();">
            &nbsp; <el-icon>
              <Refresh />
            </el-icon>
            <br>
            刷新
          </td>
          <td>&ensp;</td>
          <td>

            <el-dropdown :hide-on-click="false" trigger="click">
              <span class="el-dropdown-link">
                &nbsp; <el-icon size="default">
                  <Filter />
                </el-icon>
                <br />
                筛选行
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-checkbox v-model="selectedItems" label="FarmNumber" :checked="true">羊场编码
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item><el-checkbox v-model="selectedItems" label="FarmName" :checked="true">羊场全称
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item><el-checkbox v-model="selectedItems" label="FarmAbbreviation" :checked="true">羊场简称
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item><el-checkbox v-model="selectedItems" label="AccountsDate" :checked="true">建账日期
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item><el-checkbox v-model="selectedItems" label="DetailedAddress" :checked="true">详细地址
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item><el-checkbox v-model="selectedItems" label="FarmState" :checked="true">状态
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item><el-checkbox v-model="selectedItems" label="Principal" :checked="true">负责人
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item><el-checkbox v-model="selectedItems" label="CreateBy" :checked="true">创建人
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item><el-checkbox v-model="selectedItems" label="CreateDate" :checked="true">创建时间
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item><el-checkbox v-model="selectedItems" label="UpdateBy" :checked="true">修改人
                    </el-checkbox>
                  </el-dropdown-item>
                  <el-dropdown-item><el-checkbox v-model="selectedItems" label="UpdateDate" :checked="true">修改时间
                    </el-checkbox>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </td>
        </tr>
      </table>
    </div>
    <!-- ======================== -->

    <br />

    <br />
    <br />


    <div v-if="TagBool">
      <el-tag style="width:1920px;color: black;height: 50px;" type="danger" :iocn="Delete">
        <spna style="font-size: 15px">
          <Warning style="width: 1em; height: 1em; margin-right: 8px" color="red" />
          <span style="margin-right: 1800px">已选择 {{ TagCount }} 项</span>
        </spna>
      </el-tag>
    </div>
    <div v-else>
      <el-tag style="width:1920px;color: black;height: 50px;" type="success" :iocn="Delete">
        <spna style="font-size: 15px">
          <SuccessFilled style="width: 1em; height: 1em; margin-right: 8px" color="green" />
          <span style="margin-right: 1800px">已选择 {{ TagCount }} 项</span>
        </spna>
      </el-tag>
    </div>
    <br />
    <el-table :data="tableData" border style="width: 1920px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" width="120" fixed>
        <template v-slot="a">
          {{ a.$index + (page.pageIndex - 1) * page.pageSize + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="FarmNumber" label="羊场编码" width="185" v-if="FarmNumber" />
      <el-table-column prop="FarmName" label="羊场全称" width="100" v-if="FarmName" />
      <el-table-column prop="FarmAbbreviation" label="羊场简称" width="100" v-if="FarmAbbreviation" />
      <el-table-column prop="AccountsDate" label="建账日期" width="110" v-if="AccountsDate">
        <template v-slot="scope">
          <span>{{
            scope.row.AccountsDate ? scope.row.AccountsDate.substring(0, 10) : null
              ? scope.row.AccountsDate.substring(0, 10)
              : null }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="Principal" label="负责人" width="80" v-if="Principal" />
      <el-table-column prop="DetailedAddress" label="详细地址" width="150" v-if="DetailedAddress" />
      <el-table-column prop="Department" label="管理部门" width="100" />
      <el-table-column prop="FarmState" label="状态" width="60" v-if="FarmState">
        <template v-slot="scope">
          <span>{{ scope.row.FarmState ? "启用" : "禁用" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="CreateBy" label="创建人" width="80" v-if="CreateBy" />
      <el-table-column prop="CreateDate" label="创建时间" width="165" v-if="CreateDate">
        <template v-slot="scope">
          <span>{{
            scope.row.CreateDate
              ? scope.row.CreateDate.replace("T", " ").substring(0, 19)
              : null
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="UpdateBy" label="修改人" width="80" v-if="UpdateBy" />
      <el-table-column prop="UpdateDate" label="修改时间" width="165" v-if="UpdateDate">
        <template v-slot="scope">
          <span>{{
            scope.row.UpdateDate
              ? scope.row.UpdateDate.replace("T", " ").substring(0, 19)
              : null
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="SheepFarmId" label="操作" width="120">
        <template v-slot="scope">
          <button class="borderless-button" style="color: blue" @click="UpdSheep(scope.row)">
            编辑
          </button>
          &emsp;
          <button class="borderless-button" style="color: blue" @click="DelSheep(scope.row.SheepFarmId)">
            删除
          </button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
        :page-sizes="[1, 15, 30, 45]" :background="true" layout="slot,total, sizes, prev, pager, next, jumper"
        :total="page.pageCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
    <el-dialog v-model="dialogVisible" title="Tips" width="500" :before-close="handleClose">
      <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto"
        class="demo-ruleForm" :size="formSize" status-icon>
        <el-form-item label="羊场全称" prop="name" placeholder="请输入羊场全称">
          <el-input v-model="ruleForm.FarmName" />
        </el-form-item>
        <el-form-item label="羊场简称" prop="name" placeholder="请输入羊场简称">
          <el-input v-model="ruleForm.FarmAbbreviation" />
        </el-form-item>
        <el-form-item label="羊场规模" prop="region">
          <el-select v-model="ruleForm.FarmScale" placeholder="请输入羊场规模">
            <el-option label="500只以下" value="500只以下" />
            <el-option label="500-1000只" value="500-1000只" />
            <el-option label="1000-3000只" value="1000-3000只" />
            <el-option label="3000-5000只" value="3000-5000只" />
            <el-option label="5000只以上" value="5000只以上" />
          </el-select>
        </el-form-item>
        <el-form-item label="羊场地址" prop="region">
          <el-cascader size="large" :options="pcaTextArr" v-model="selectedOptions" @change="handleChange" clearable />
        </el-form-item>
        <el-form-item label="详细地址" prop="name" placeholder="请输入详细地址">
          <el-input v-model="ruleForm.DetailedAddress" />
        </el-form-item>
        <el-form-item label="建账时间" required>
          <el-col :span="11">
            <el-form-item prop="date1">
              <el-date-picker v-model="ruleForm.AccountsDate" type="date" label="Pick a date" placeholder="Pick a date"
                value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="负责人" prop="resource" placeholder="请输选择负责人">
          <el-select v-model="ruleForm.Principal" placeholder="请选择负责人">
            <el-option label="张三" value="张三" />
            <el-option label="李四" value="李四" />
            <el-option label="王五" value="王五" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理部门" prop="resource" placeholder="请输选择部门">
          <el-select v-model="ruleForm.Department" placeholder="请选择负责人">
            <el-option label="财务部" value="财务部" />
            <el-option label="人事部" value="人事部" />
            <el-option label="开发部" value="开发部" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="resource">
          <el-radio-group v-model="ruleForm.FarmState">
            <el-radio :value="true">启用</el-radio>
            <el-radio :value="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>
<script setup lang="ts">
import { watch, ref, reactive, inject, onMounted } from "vue";
import type {
  ComponentSize,
  FormInstance,
  FormRules,
  ElTable,
  TagProps,
} from "element-plus";
import {
  Plus,
  Search,
  Delete,
  DocumentChecked,
  Back,
  Warning,
  SuccessFilled
} from '@element-plus/icons-vue'
import { regionData, codeToText, pcaTextArr } from "element-china-area-data";
import { ArrowDown } from "@element-plus/icons-vue";
import { Filter } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import http from '@/http'


const FarmNumber = ref(true); //羊场编码
const FarmName = ref(true); //羊场全称
const FarmAbbreviation = ref(true); //羊场简称
const AccountsDate = ref(true); //建账日期
const DetailedAddress = ref(true); //详细地址
const FarmState = ref(true); //状态
const Principal = ref(true); //负责人
const CreateBy = ref(true); //创建人
const CreateDate = ref(true); //创建时间
const UpdateBy = ref(true); //修改人
const UpdateDate = ref(true); //修改时间

const selectedItems = ref([] as string[]);
// 监听 myVar 的变化
watch(selectedItems, (newValue, oldValue) => {
  // 遍历属性，根据 selectedItems 的值来设置对应属性的值
  FarmNumber.value = selectedItems.value.includes("FarmNumber");
  FarmName.value = selectedItems.value.includes("FarmName");
  FarmAbbreviation.value = selectedItems.value.includes("FarmAbbreviation");
  AccountsDate.value = selectedItems.value.includes("AccountsDate");
  DetailedAddress.value = selectedItems.value.includes("DetailedAddress");
  FarmState.value = selectedItems.value.includes("FarmState");
  Principal.value = selectedItems.value.includes("Principal");
  CreateBy.value = selectedItems.value.includes("CreateBy");
  CreateDate.value = selectedItems.value.includes("CreateDate");
  UpdateBy.value = selectedItems.value.includes("UpdateBy");
  UpdateDate.value = selectedItems.value.includes("UpdateDate");

  console.log(FarmNumber.value, FarmName.value, FarmAbbreviation.value);
});

const Checkoption = ref([
  { label: "Option 1", value: "option1" },
  { label: "Option 2", value: "option2" },
  { label: "Option 3", value: "option3" },
  { label: "Option 4", value: "option4" },
]);

//省市区
const option = ref(regionData);

let selectedOptions = ref([] as string[]);

//获取省市区
const handleChange = (data: any) => {
  console.log(data);
  ruleForm.SheepAddress = data.join(",");
  console.log(ruleForm.SheepAddress);
};

const dialogVisible = ref(false);


//true为添加。false为修改
const AddAndUpd = ref(true);

const tableData = ref([]);

const handleClose = () => {
  dialogVisible.value = false;
};
const SelTo = reactive({
  name: "",
  pname: "",

})

const page = reactive({
  pageIndex: 1,
  pageSize: 15,
  totalCount: 0,
  pageCount: 0
})

//每页显示条数
const handleSizeChange = (val: number) => {
  page.pageSize = val;
  LoadData();
}
//当前页索引
const handleCurrentChange = (val: number) => {
  page.pageIndex = val;
  LoadData();
}

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<RuleForm[]>([])
// const toggleSelection = (rows?: RuleForm[]) => {
//   if (rows) {
//     rows.forEach((row) => {

//       multipleTableRef.value!.toggleRowSelection(row, undefined)
//     })
//   } else {
//     multipleTableRef.value!.clearSelection()
//   }
// }
let ids = "";
const TagBool = ref(true);
const TagCount = ref(0);
const handleSelectionChange = (val: RuleForm[]) => {
  ids = "";
  multipleSelection.value = val
  console.log(multipleSelection)
  multipleSelection.value.forEach(x => {
    ids += x.SheepFarmId + ",";
  })
  ids = ids.substring(0, ids.length - 1);

  TagCount.value = ids.split(',').length;
  if (ids == "") {
    TagCount.value = 0;
  }
  if (TagCount.value == 0) {
    TagBool.value = true;
  }
  else {
    TagBool.value = false;
  }

}

const DelAll = () => {
  http
    .get("Organization/api/SheepFarm/HandleDelAllSheepFarm?ids=" + ids)
    .then((res) => {
      if (res.data > 0) {
        ElMessage({
          type: "error",
          message: "删除成功",
          duration: 2000
        });
        LoadData();
      } else {
        ElMessage({
          type: "error",
          message: "删除失败",
          duration: 2000
        });
      }
    });
}
const LoadData = () => {
  http
    .get("OrganizationRead/api/SheepFarm/HandleGetSheepFarm", {
      params: {
        FarmName: SelTo.name,
        Principal: SelTo.pname,
        Index: page.pageIndex,
        Size: page.pageSize,
      },
    })
    .then((res) => {
      console.log(res.data);
      tableData.value = res.data.datas;
      page.totalCount = res.data.totalCount
      page.pageCount = res.data.pageCount
    });
};
const AddSheep = () => {
  dialogVisible.value = false;
};

interface RuleForm {
  SheepFarmId: string;
  FarmNumber: string;
  FarmName: string;
  FarmAbbreviation: string;
  FarmScale: string;
  AccountsDate: string;
  Principal: string;
  SheepAddress: string;
  DetailedAddress: string;
  Department: string;
  FarmState: boolean;
}

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
let ruleForm = reactive<RuleForm>({
  SheepFarmId: "0",
  FarmNumber: "",
  FarmName: "",
  FarmAbbreviation: "",
  FarmScale: "",
  AccountsDate: "",
  Principal: "",
  SheepAddress: "",
  DetailedAddress: "",
  Department: "",
  FarmState: true,
});

const locationOptions = ["Home", "Company", "School"];

let rules = reactive<FormRules<RuleForm>>({
  FarmName: [
    { required: true, message: "Please input Activity name", trigger: "blur" },
  ],
  FarmAbbreviation: [
    {
      required: true,
      message: "Please select Activity zone",
      trigger: "change",
    },
  ],
  AccountsDate: [
    {
      required: true,
      message: "Please select Activity count",
      trigger: "change",
    },
  ],
  Principal: [
    {
      type: "date",
      required: true,
      message: "Please pick a date",
      trigger: "change",
    },
  ],
});


const AddNew = () => {
  ruleForm.SheepFarmId = "0";
  ruleForm.FarmNumber = " ";
  ruleForm.FarmName = " ";
  ruleForm.FarmAbbreviation = " ";
  ruleForm.FarmScale = " ";
  ruleForm.AccountsDate = " ";
  ruleForm.Principal = " ";
  ruleForm.SheepAddress = " ";
  ruleForm.DetailedAddress = " ";
  ruleForm.Department = " ";
  ruleForm.FarmState = true;
  dialogVisible.value = true;
  AddAndUpd.value = true;
};
const submitForm = async (formEl: FormInstance | undefined) => {
  console.log(AddAndUpd);

  if (!formEl) return;

  if (AddAndUpd.value == true) {
    await formEl.validate((valid, fields) => {
      if (valid) {
        http.post("Organization/api/SheepFarm/HandleAddSheepFarm", ruleForm)
          .then((res) => {
            if (res.data > 0) {
              ElMessage({
                type: "success",
                message: "添加成功",
                duration: 2000
              });
              LoadData();
            } else {
              ElMessage({
                type: "error",
                message: "添加失败",
                duration: 2000
              });
            }
          });
      } else {
        console.log("error submit!", fields);
      }
    });
  } else {
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log(ruleForm);
        http
          .post("Organization/api/SheepFarm/HandleUpdSheepFarm", ruleForm)
          .then((res) => {
            if (res.data > 0) {
              ElMessage({
                type: "success",
                message: "修改失败",
                duration: 2000
              });
              LoadData();
            } else {
              ElMessage({
                type: "error",
                message: "修改失败",
                duration: 2000
              });
            }
          });
      } else {
        console.log("error submit!", fields);
      }
    });
  }

  selectedOptions.value = [];
  dialogVisible.value = false;
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const DelSheep = (id: string) => {
  ElMessageBox.confirm(
    '确定要删除当前数据吗?',
    '警告',
    {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    }
  ).then(() => {
    http
      .get("Organization/api/SheepFarm/HandleDelSheepFarm?SheepFarmId=" + id)
      .then((res) => {
        if (res.data > 0) {
          ElMessage({
            type: "success",
            message: "删除成功",
            duration: 2000
          });
          LoadData();
        } else {
          ElMessage({
            type: "error",
            message: "删除失败",
            duration: 2000
          });


        }
      });


  })




};

const UpdSheep = (sheeplist: FormInstance | any) => {
  console.log(sheeplist);
  const list = { ...sheeplist };
  //若有报错，请忽略。经测试虽然报错，但还是可以正常实现功能，且控制台不显示报错

  ruleForm = sheeplist;

  // ruleForm.SheepFarmId = list.SheepFarmId;
  // ruleForm.FarmNumber = list.FarmNumber;
  // ruleForm.FarmName = list.FarmName;
  // ruleForm.FarmAbbreviation = list.FarmAbbreviation;
  // ruleForm.FarmScale = list.FarmScale;
  // ruleForm.AccountsDate = list.AccountsDate;
  // ruleForm.Principal = list.Principal;
  // ruleForm.SheepAddress = list.SheepAddress;
  // ruleForm.DetailedAddress = list.DetailedAddress;
  // ruleForm.Department = list.Department;
  // ruleForm.FarmState = list.FarmState;
  selectedOptions.value = ruleForm.SheepAddress.split(",");
  console.log(selectedOptions);
  AddAndUpd.value = false;
  dialogVisible.value = true;
};
const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));

onMounted(() => {
  LoadData();
});
</script>
<style>
.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.borderless-button {
  background: none;
  border: none;
  color: #333;
  /* 按钮文字颜色 */
  cursor: pointer;
  font-size: 14px;
  /* 按钮文字大小 */
}
</style>